package cn.iocoder.yudao.module.enterprise.controller.admin.report;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.carbon.api.accountboundary.AccountBoundaryApi;
import cn.iocoder.yudao.module.carbon.api.accountboundary.dto.AccountBoundaryRespDTO;
import cn.iocoder.yudao.module.enterprise.controller.admin.account.vo.AccountSourceDetailRespVO;
import cn.iocoder.yudao.module.enterprise.controller.admin.report.vo.*;
import cn.iocoder.yudao.module.enterprise.controller.admin.reportdownload.vo.ReportDownloadCreateReqVO;
import cn.iocoder.yudao.module.enterprise.convert.reductionscene.ReductionSceneConvert;
import cn.iocoder.yudao.module.enterprise.convert.report.ReportConvert;
import cn.iocoder.yudao.module.enterprise.convert.report.ReportReductionConvert;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.account.AccountDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.boundary.BoundaryDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.emissionbasis.BasisValueDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.emissionbasis.EmissionBasisDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.organization.OrganizationDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.reductionscene.ReductionSceneDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.report.ReportDO;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.report.ReportReductionDO;
import cn.iocoder.yudao.module.enterprise.enums.report.ReportTypeEnum;
import cn.iocoder.yudao.module.enterprise.service.account.AccountService;
import cn.iocoder.yudao.module.enterprise.service.account.AccountSourceService;
import cn.iocoder.yudao.module.enterprise.service.boundary.BoundaryService;
import cn.iocoder.yudao.module.enterprise.service.emissionbasis.BasisValueService;
import cn.iocoder.yudao.module.enterprise.service.emissionbasis.EmissionBasisService;
import cn.iocoder.yudao.module.enterprise.service.emissionsource.EmissionGaseService;
import cn.iocoder.yudao.module.enterprise.service.organization.OrganizationService;
import cn.iocoder.yudao.module.enterprise.service.reductionscene.ReductionSceneService;
import cn.iocoder.yudao.module.enterprise.service.report.ReportReductionService;
import cn.iocoder.yudao.module.enterprise.service.report.ReportService;
import cn.iocoder.yudao.module.enterprise.service.reportdownload.ReportDownloadService;
import cn.iocoder.yudao.module.enterprise.util.WordUtils;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.REPORT_TYPE_NOT_EXISTS;

@Tag(name = "管理后台 - 核算报告")
@RestController
@RequestMapping("/enterprise/report")
@Validated
public class ReportController {

    @Resource
    private ReportService reportService;
    @Resource
    private AccountService accountService;
    @Resource
    private BasisValueService basisValueService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private BoundaryService boundaryService;
    @Resource
    private EmissionBasisService emissionBasisService;
    @Resource
    private ReportReductionService reportReductionService;
    @Resource
    private ReductionSceneService reductionSceneService;
    @Resource
    private AccountSourceService accountSourceService;
    @Resource
    private EmissionGaseService emissionGaseService;
    @Resource
    private ReportDownloadService reportDownloadService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private AccountBoundaryApi accountBoundaryApi;
    @Resource
    private FileApi fileApi;

    @PostMapping("/create")
    @Operation(summary = "创建核算报告")
    @PreAuthorize("@ss.hasPermission('enterprise:report:create')")
    public CommonResult<Long> createReport(@Valid @RequestBody ReportCreateReqVO createReqVO) {
        return success(reportService.createReport(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新核算报告")
    @PreAuthorize("@ss.hasPermission('enterprise:report:update')")
    public CommonResult<Boolean> updateReport(@Valid @RequestBody ReportUpdateReqVO updateReqVO) {
        reportService.updateReport(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除核算报告")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('enterprise:report:delete')")
    public CommonResult<Boolean> deleteReport(@RequestParam("id") Long id) {
        reportService.deleteReport(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得核算报告")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('enterprise:report:query')")
    public CommonResult<ReportRespVO> getReport(@RequestParam("id") Long id) {
        return success(reportService.getReport(id));
    }

    @GetMapping("/page")
    @Operation(summary = "获得核算报告分页")
    @PreAuthorize("@ss.hasPermission('enterprise:report:query')")
    public CommonResult<PageResult<ReportPageRespVO>> getReportPage(@Valid ReportPageReqVO pageVO) {
        // 获取核算报告分页列表
        PageResult<ReportDO> pageResult = reportService.getReportPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }

        // 获得拼接需要的数据
        List<Long> accountIds = convertList(pageResult.getList(), ReportDO::getAccountId);
        Map<Long, AccountDO> accountMap = accountService.getAccountMap(accountIds);

        List<String> userIds = convertList(pageResult.getList(), ReportDO::getUpdater);
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds.stream().map(Long::parseLong).collect(Collectors.toList()));

        // 拼接结果返回
        ArrayList<ReportPageRespVO> reportList = new ArrayList<>();
        pageResult.getList().forEach(report -> {
            ReportPageRespVO respVO = ReportConvert.INSTANCE.convert02(report);
            // 拼接核算信息
            AccountDO account = accountMap.get(report.getAccountId());
            respVO.setAccountCycleType(account.getCycleType())
                    .setAccountYear(account.getYear())
                    .setAccountCycle(account.getCycle())
                    .setTotalEmission(account.getTotal());
            // 拼接排放基准信息
            EmissionBasisDO emissionBasis = emissionBasisService.getEmissionBasisByCategory(account.getCycleType());
            BasisValueDO basisValue = basisValueService.getBasisValueByBasisIdAndTimeInterval(emissionBasis.getId(), account.getCycle());
            respVO.setBasisEmission(basisValue.getTotalRelease());

            // 拼接更新者信息
            AdminUserRespDTO user = userMap.get(Long.parseLong(report.getUpdater()));
            respVO.setUpdater(user.getNickname());

            reportList.add(respVO);
        });

        return success(new PageResult<>(reportList, pageResult.getTotal()));
    }

    @PostMapping("/create-reduction")
    @Operation(summary = "创建核算报告的减排信息")
    @PreAuthorize("@ss.hasPermission('enterprise:report:create')")
    public CommonResult<Long> createReportReduction(@Valid @RequestBody ReportReductionCreateReqVO createReqVO) {
        return success(reportReductionService.createReportReduction(createReqVO));
    }

    @DeleteMapping("/delete-reduction")
    @Operation(summary = "删除核算报告的减排信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('enterprise:report:delete')")
    public CommonResult<Boolean> deleteReportReduction(@RequestParam("id") Long id) {
        reportReductionService.deleteReportReduction(id);
        return success(true);
    }

    @GetMapping("/page-reduction")
    @Operation(summary = "获得核算报告的减排信息分页")
    @PreAuthorize("@ss.hasPermission('enterprise:report:query')")
    public CommonResult<PageResult<ReportReductionRespVO>> getReportReductionPage(@Valid ReportReductionPageReqVO pageVO) {
        // 获取核算报告分页列表
        PageResult<ReportReductionDO> pageResult = reportReductionService.getReportReductionPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(new PageResult<>(pageResult.getTotal()));
        }

        // 获得拼接需要的数据
        List<Long> reductionSceneIds = convertList(pageResult.getList(), ReportReductionDO::getReductionId);
        Map<Long, ReductionSceneDO> reductionSceneMap = reductionSceneService.getReductionSceneMap(reductionSceneIds);

        // 拼接结果返回
        List<ReportReductionRespVO> respList = new ArrayList<>();
        pageResult.getList().forEach(reportReduction -> {
            ReportReductionRespVO respVO = ReportReductionConvert.INSTANCE.convert(reportReduction);

            // 拼接减排信息
            ReductionSceneDO reductionScene = reductionSceneMap.get(reportReduction.getReductionId());
            respVO.setReductionScene(ReductionSceneConvert.INSTANCE.convert(reductionScene));

            respList.add(respVO);
        });

        return success(new PageResult<>(respList, pageResult.getTotal()));
    }

    @GetMapping("/export-word")
    @Operation(summary = "生成核算报告 Word")
    @PreAuthorize("@ss.hasPermission('enterprise:report:export')")
    public CommonResult<String> exportReportWord(@Valid ReportExportReqVO reqVO) {
        // 存储报告中的动态数据
        ReportExportRespVO respVO = new ReportExportRespVO();

        // 报告类型
        String fileName;
        String templateName;
        String standard;
        if (reqVO.getReportType().equals(ReportTypeEnum.ISO_GREENHOUSE_GAS_INVENTORY.getType())) {
            // 导出温室气体盘查报告（ISO）
            fileName = "温室气体盘查报告（ISO）";
            templateName = "温室气体盘查报告（ISO）";
            standard = "ISO";
        } else if (reqVO.getReportType().equals(ReportTypeEnum.GHG_GREENHOUSE_GAS_INVENTORY.getType())) {
            // 导出温室气体盘查报告（GHG）
            fileName = "温室气体盘查报告（GHG）";
            templateName = "温室气体盘查报告（GHG）";
            standard = "GHG";
        } else {
            throw exception(REPORT_TYPE_NOT_EXISTS);
        }

        // 报告编制时间
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_YEAR_MONTH_DAY);
        String reportTime = sdf.format(new Date());
        respVO.setReportTime(reportTime);

        // 核算报告
        ReportRespVO report = reportService.getReport(reqVO.getId());
        respVO.setReductionAdvice(report.getReductionAdvice());

        // 组织基本信息
        OrganizationDO organization = organizationService.getOrganizationByPlanId(report.getPlanId());
        respVO.setOrganizationName(organization.getName());
        respVO.setOrganizationProfile(organization.getProfile());
        respVO.setOrganizationRegisteredAddr(organization.getRegisteredAddr() + " " + organization.getRegisteredAddrDetail());
        respVO.setOrganizationBizAddr(organization.getBizAddr() + " " + organization.getBizAddrDetail());

        // 组织边界
        BoundaryDO boundary = boundaryService.getBoundaryByPlanId(report.getPlanId());
        Byte method = boundary.getMethod();
        String methodStr = "";
        if (method == 0) {
            methodStr = "股份比例法";
        } else if (method == 1) {
            methodStr = "财务控制权";
        } else if (method == 2) {
            methodStr = "运营控制权";
        }
        respVO.setBoundaryMethod(methodStr);
        respVO.setBoundaryDesc(boundary.getBoundaryDesc());
        respVO.setBoundaryChangeDesc(boundary.getChangeDesc());

        // 排放源
        List<AccountSourceDetailRespVO> accountSourceDetailList = accountSourceService.getAccountSourceDetailList(report.getAccountId());
        // 核算边界id和排放源列表的Map
        Map<String, List<AccountSourceDetailRespVO>> accountBoundarySourceMap = new HashMap<>();
        accountSourceDetailList.forEach(x -> {
            // 获取核算边界
            AccountBoundaryRespDTO accountBoundaryRespDTO = null;
            if (standard.equals("ISO")) {
                accountBoundaryRespDTO = accountBoundaryApi.getAccountBoundary(standard, x.getIsoClassification(), x.getIsoCategory()).getCheckedData();
            } else if (standard.equals("GHG")) {
                accountBoundaryRespDTO = accountBoundaryApi.getAccountBoundary(standard, x.getGhgClassification(), x.getGhgCategory()).getCheckedData();
            }
            String accountBoundaryId = String.valueOf(accountBoundaryRespDTO.getId());
            List<AccountSourceDetailRespVO> accountSourceDetailRespVOList = null;
            if (accountBoundarySourceMap.get(accountBoundaryId) != null) {
                accountSourceDetailRespVOList = accountBoundarySourceMap.get(accountBoundaryId);
            } else {
                accountSourceDetailRespVOList = new ArrayList<>();
            }
            accountSourceDetailRespVOList.add(x);
            accountBoundarySourceMap.put(accountBoundaryId, accountSourceDetailRespVOList);
        });

        // 核算边界id和排放源集合字符串的Map
        Map<String, String> accountSourceMap = new HashMap<>();
        accountBoundarySourceMap.forEach((x, y) -> accountSourceMap.put(x, y.stream().map(AccountSourceDetailRespVO::getName).collect(Collectors.joining(","))));
        respVO.setEmissionSourceMap(accountSourceMap);

        // 排放源分类和排放量的Map
        Map<String, ReportExportRespVO.EmissionRate> classificationRateMap = new HashMap<>();

        Map<String, Double> classificationMap = new HashMap<>();
        for (Map.Entry<String, List<AccountSourceDetailRespVO>> entry : accountBoundarySourceMap.entrySet()) {
            String key = entry.getKey();
            List<AccountSourceDetailRespVO> value = entry.getValue();

            double emissionValue = 0;
            AccountBoundaryRespDTO accountBoundary = accountBoundaryApi.getAccountBoundaryById(Long.valueOf(key)).getCheckedData();
            if (classificationMap.get(accountBoundary.getClassification()) != null) {
                emissionValue = classificationMap.get(accountBoundary.getClassification());
            }
            emissionValue += value.stream().mapToDouble(AccountSourceDetailRespVO::getEmissionTotal).sum();
            classificationMap.put(accountBoundary.getClassification(), emissionValue);
        }

        // 计算总排放量
        double emissionTotal = classificationMap.values().stream().mapToDouble(Double::doubleValue).sum();
        classificationMap.forEach((k, v) -> {
            ReportExportRespVO.EmissionRate emissionRate = new ReportExportRespVO.EmissionRate();
            emissionRate.setEmission(v).setRate(v / emissionTotal * 100);
            classificationRateMap.put(k, emissionRate);
        });
        classificationRateMap.put("总计", new ReportExportRespVO.EmissionRate().setEmission(emissionTotal).setRate(100D));
        respVO.setClassificationRateMap(classificationRateMap);

        List<AccountSourceDetailRespVO> emissionScopeList1 = accountSourceDetailList.stream().filter(e -> "范围一".equals(e.getGhgClassification())).collect(Collectors.toList());
        List<AccountSourceDetailRespVO> emissionScopeList2 = accountSourceDetailList.stream().filter(e -> "范围二".equals(e.getGhgClassification())).collect(Collectors.toList());

        // 每种温室气体之直接排放
        List<ReportExportRespVO.EmissionRate> gasEmissionScope1List = calculateGasEmission(emissionScopeList1);
        respVO.setGasEmissionScope1List(gasEmissionScope1List);
        // 每种温室气体之能源间接排放量
        List<ReportExportRespVO.EmissionRate> gasEmissionScope2List = calculateGasEmission(emissionScopeList2);
        respVO.setGasEmissionScope2List(gasEmissionScope2List);
        // 每种温室气体总排放量
        List<AccountSourceDetailRespVO> emissionScopeList = new ArrayList<>();
        Stream.of(emissionScopeList1, emissionScopeList2).forEach(emissionScopeList::addAll);
        List<ReportExportRespVO.EmissionRate> gasEmissionTotalList = calculateGasEmission(emissionScopeList);
        respVO.setGasEmissionTotalList(gasEmissionTotalList);

        // 排放源之直接排放
        List<ReportExportRespVO.EmissionGase> emissionGaseScope1List = getEmissionGase(emissionScopeList1);
        respVO.setEmissionGaseScope1List(emissionGaseScope1List);
        // 排放源之能源间接排放
        List<ReportExportRespVO.EmissionGase> emissionGaseScope2List = getEmissionGase(emissionScopeList2);
        respVO.setEmissionGaseScope2List(emissionGaseScope2List);

        // 排放源数据质量
        List<ReportExportRespVO.EmissionDataQuality> dataQualityList = new ArrayList<>();
        for (AccountSourceDetailRespVO source : emissionScopeList) {
            Integer adScore = source.getDataScore();
            Integer efScore = source.getFactorScore();
            Double avgScore = (adScore + efScore) / 2.0;
            Integer dataLevel = getDataLevel(avgScore);

            ReportExportRespVO.EmissionDataQuality dataQuality = new ReportExportRespVO.EmissionDataQuality();
            dataQuality.setName(source.getName())
                    .setAdScore(adScore)
                    .setEfScore(efScore)
                    .setAvgScore(avgScore)
                    .setLevel(dataLevel)
                    .setEmission(source.getEmissionTotal());
            dataQualityList.add(dataQuality);
        }
        // 计算总排放量
        double emissionSum = dataQualityList.stream().mapToDouble(ReportExportRespVO.EmissionDataQuality::getEmission).sum();
        // 计算排放占比、加权平均分
        dataQualityList = dataQualityList.stream().map(e -> {
            double emissionRate = e.getEmission() / emissionSum;
            e.setEmissionRate(emissionRate * 100)
                    .setWeightAveScore(e.getAvgScore() * emissionRate);
            return e;
        }).collect(Collectors.toList());
        respVO.setEmissionDataQualityList(dataQualityList);
        // 计算加权平均积分、数据质量等级
        double weightAveScore = dataQualityList.stream().mapToDouble(ReportExportRespVO.EmissionDataQuality::getWeightAveScore).sum();
        Integer dataLevel = getDataLevel(weightAveScore);
        respVO.setEmissionSum(emissionSum)
                .setWeightAveScore(weightAveScore)
                .setDataLevel(dataLevel);

        // 碳排放核算
        AccountDO account = accountService.getAccount(report.getAccountId());
        String year = account.getYear();
        Integer cycleType = account.getCycleType();
        String cycle = account.getCycle();
        String accountCycle = "";
        if (cycleType.equals(1)) {
            accountCycle = year + "年";
        } else if (cycleType.equals(2)) {
            accountCycle = year + "年第" + cycle + "季度";
        } else if (cycleType.equals(3)) {
            accountCycle = year + "年" + cycle + "月";
        }
        respVO.setAccountCycle(accountCycle);
        respVO.setAccountTotal(emissionTotal);

        // 排放基准
        EmissionBasisDO emissionBasis = emissionBasisService.getEmissionBasisByCategory(account.getCycleType());
        respVO.setEmissionBasisYear(emissionBasis.getYear());

        // 减排场景
        List<ReportReductionDO> reportReductionList = reportReductionService.getReportReductionListByReportId(report.getId());
        List<Long> reductionIds = convertList(reportReductionList, ReportReductionDO::getReductionId);
        List<ReductionSceneDO> reductionSceneList = reductionSceneService.getReductionSceneList(reductionIds);
        respVO.setReductionSceneList(reductionSceneList);

        // 同比核算
        Long lastAccountId = account.getLastAccount();
        AccountDO lastAccount = accountService.getAccount(lastAccountId);
        Double lastAccountTotal = lastAccount.getTotal();
        respVO.setLastAccountTotal(lastAccountTotal);
        Double lastAccountRate = (lastAccountTotal - emissionTotal) / lastAccountTotal * 100;
        respVO.setLastAccountRate(lastAccountRate);

        // 使用Map存储数据
        HashMap<Object, Object> data = new HashMap<>();
        data.put("report", respVO);

        // 生成word
        byte[] fileBytes = WordUtils.getDocBytes(data, templateName + ".ftl");
        // 上传至文件服务器
        String uploadFileName = fileName + "_" + System.currentTimeMillis() + "_" + reportTime + ".docx";
        String fileUrl = fileApi.createFile(uploadFileName, fileBytes);
        // 插入报告下载记录
        ReportDownloadCreateReqVO reportDownloadCreateReqVO = new ReportDownloadCreateReqVO();
        reportDownloadCreateReqVO.setReportId(reqVO.getId())
                .setType(reqVO.getReportType())
                .setFileName(uploadFileName)
                .setReportUrl(fileUrl);
        reportDownloadService.createReportDownload(reportDownloadCreateReqVO);
        return success(fileUrl);
    }

    private List<ReportExportRespVO.EmissionRate> calculateGasEmission(List<AccountSourceDetailRespVO> emissionScopeList) {
        Map<Integer, Double> resultMap = new TreeMap<>();
        List<ReportExportRespVO.EmissionRate> resultList = new ArrayList<>();

        if (emissionScopeList.isEmpty()) {
            ReportExportRespVO.EmissionRate emissionRate = new ReportExportRespVO.EmissionRate();
            emissionRate.setEmission(0D)
                    .setRate(0D);
            resultList.add(emissionRate);
            resultList.add(emissionRate);
            resultList.add(emissionRate);
            return resultList;
        }

        // 每个排放源的温室气体
        for (AccountSourceDetailRespVO respVO : emissionScopeList) {
            Map<Integer, Double> emissionGaseMap = emissionGaseService.getEmissionGaseMap(respVO.getSourceId(), respVO.getDataValue(), respVO.getGwp());
            for (Map.Entry<Integer, Double> entry : emissionGaseMap.entrySet()) {
                double count = resultMap.containsKey(entry.getKey()) ? entry.getValue() : 0;
                resultMap.put(entry.getKey(), count + entry.getValue());
            }
        }

        // 计算温室气体总和
        double sum = resultMap.values().stream().mapToDouble(Double::doubleValue).sum();
        for (Map.Entry<Integer, Double> entry : resultMap.entrySet()) {
            Double value = entry.getValue();
            ReportExportRespVO.EmissionRate result = new ReportExportRespVO.EmissionRate();
            result.setEmission(value).setRate(value / sum * 100);
            resultList.add(result);
        }
        return resultList;
    }

    private List<ReportExportRespVO.EmissionGase> getEmissionGase(List<AccountSourceDetailRespVO> emissionScopeList) {
        List<ReportExportRespVO.EmissionGase> emissionGaseList = new ArrayList<>();
        if (emissionScopeList.isEmpty()) {
            ReportExportRespVO.EmissionGase emissionGase = new ReportExportRespVO.EmissionGase();
            emissionGase.setName("")
                    .setFacility("")
                    .setCo2(0D)
                    .setCh4(0D)
                    .setN2o(0D)
                    .setHfcs(0D)
                    .setPfcs(0D)
                    .setSf6(0D)
                    .setNf3(0D)
                    .setTotal(0D);
            emissionGaseList.add(emissionGase);
            return emissionGaseList;
        }
        for (AccountSourceDetailRespVO e : emissionScopeList) {
            Map<Integer, Double> map = emissionGaseService.getEmissionGaseMap(e.getSourceId(), e.getDataValue(), e.getGwp());
            // 计算总排放量
            double total = map.values().stream().mapToDouble(Double::doubleValue).sum();
            ReportExportRespVO.EmissionGase emissionGase = new ReportExportRespVO.EmissionGase();
            emissionGase.setName(e.getName())
                    .setFacility(e.getFacility())
                    .setCo2(map.get(0))
                    .setCh4(map.get(1))
                    .setN2o(map.get(2))
                    .setHfcs(map.get(3))
                    .setPfcs(map.get(4))
                    .setSf6(map.get(5))
                    .setNf3(map.get(6))
                    .setTotal(total);
            emissionGaseList.add(emissionGase);
        }
        return emissionGaseList;
    }

    private Integer getDataLevel(Double avgScore) {
        if (avgScore < 2.0) {
            return 5;
        } else if (avgScore < 3.0) {
            return 4;
        } else if (avgScore < 4.0) {
            return 3;
        } else if (avgScore < 5.0) {
            return 2;
        }
        return 1;
    }

}
